package cn.sjtu.algorithm.array_sort;

import java.util.Arrays;

/**
 * @author syo 2319615164@qq.com
 * @description
 * @date 2024/5/16
 * @Copyright syo
 */
public class MergeSort {

    private static int[] temp;

    public static void main(String[] args) {
        int[] nums = {9, 1, 8, 2, 7, 3, 6, 4, 5, 0};
        mergeSort(nums, 0, nums.length - 1);
        System.out.println(Arrays.toString(nums));
    }

    public static void mergeSort(int[] nums, int l, int r) {
        if (l >= r) {
            return;
        }

        int mid = l + (r - l) / 2;
        mergeSort(nums, l, mid);
        mergeSort(nums, mid + 1, r);
        int i = l;
        int j = mid + 1;
        int k = 0;
        temp = new int[nums.length];
        while (i <= mid && j <= r) {
            if (nums[i] <= nums[j]) {
                temp[k++] = nums[i++];
            } else {
                temp[k++] = nums[j++];
            }
        }

        while (i <= mid) {
            temp[k++] = nums[i++];
        }
        while (j <= r) {
            temp[k++] = nums[j++];
        }

        for (i = 0; i < k; i++) {
            nums[l + i] = temp[i];
        }
    }
}
